package com.drk.skifree;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener;

import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;

import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;

import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground;
import org.anddev.andengine.entity.scene.menu.MenuScene;
import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.anddev.andengine.entity.scene.menu.item.IMenuItem;
import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSCounter;
import org.anddev.andengine.entity.util.FPSLogger;

import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.opengl.texture.source.AssetTextureSource;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;



import android.graphics.Color;
import android.graphics.Typeface;

import android.hardware.SensorManager;

import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;


public class SkiFreeActivity extends BaseGameActivity implements IOnSceneTouchListener, IOnMenuItemClickListener  {

    // ===========================================================
    // Constants
    // ===========================================================
	private static final String TAG = "Coin";
    private static final int CAMERA_WIDTH = 480;
    private static final int CAMERA_HEIGHT = 720;
    protected static final int MENU_RESET = 0;
	protected static final int MENU_OPTIONS = MENU_RESET + 1;
	protected static final int MENU_HELP = MENU_RESET + 2;
	protected static final int MENU_QUIT = MENU_RESET + 3;
	protected MenuScene mMenuScene;
    // ===========================================================
    // Fields
    // ===========================================================
    public float nDistance = 0;
    public int maxobjs = 0;
    private Sprite finish;
    Sprite back1;
    Sprite back2;
    Sprite slalomStart;
   Sprite freestyleStart;
    
    private Texture mTextureSheet;
    private TextureRegion[] mTextureRegionSheet;
    
    private TiledTextureRegion mTiledTexturePlayer;
    
    private AnimatedSprite mPlayer;
    private Camera mCamera;
    
   // private RepeatingSpriteBackground mBackground;
   // private Texture mBackTex;
   // private TextureRegion mBackTexReg;
    
    private SensorManager sensorManager;

    private float accellerometerSpeedX;
    private float accellerometerSpeedY;
    private int sX, sY; // Sprite coordinates
	private Texture mTexturePlayer;
	// HUD/FPS
	private Texture mFontTexture;
	private Font mFont;
	private Font mFontScore;
	private Texture mOnScreenControlTexture;
	private TextureRegion mOnScreenControlBaseTextureRegion;
	private TextureRegion mOnScreenControlKnobTextureRegion;
	private static ObjectPoolDrk Drk_POOL;
	
	
	//Flags
	private Texture mFlagsRightTexture;
	private Texture mFlagsLeftTexture;
	private TiledTextureRegion mLeftTextureRegion;
	private TiledTextureRegion mRightTextureRegion;
	
	private Texture mFinishTexture;
	private Texture mStartTexture;
	private TextureRegion mStartTextReg;
	private TextureRegion mFinTextReg;
	
	private Texture mRanger;
	private TiledTextureRegion mRangerTextReg;
	
	
	//Menu
	private Texture mMenuText;
	private TextureRegion mMenuRestartReg;
	private TextureRegion mMenuOptionsReg;
	private TextureRegion mMenuHelpReg;
	private TextureRegion mMenuExitReg;
	
	//Splash screen
	private Texture mSplashText;
	private TextureRegion mSplashtextReg;
	
	private Texture mFontTextureScore;
    // ===========================================================
    // Constructors
    // ===========================================================

    // ===========================================================
    // Getter & Setter
    // ===========================================================

    // ===========================================================
    // Methods for/from SuperClass/Interfaces
    // ===========================================================
@Override
public void onDestroy()
{
	super.onDestroy();
	//sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
//sensorManager.unregisterListener(this);//.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_GAME);

	}
    public Engine onLoadEngine() {
    	
    	Log.v("Coin", "onloadengine");
        this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
        final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera);
		engineOptions.getTouchOptions().setRunOnUpdateThread(true);
		return new Engine(engineOptions);
        //return new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
    }

    public void onLoadResources() {
    	Log.v("Coin", "onloadres");
    	this.mTextureSheet = new Texture(512,512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
    	
    	 TextureRegionFactory.createFromAsset(mTextureSheet, this, "gfx/skinewset.png", 0, 0);
    	this.mTextureRegionSheet = new TextureRegion[24];
    	int cnt = 0;
    	for(int y = 0;y <= 3;y++)
    	{
    		for(int x = 0;x <= 3;x++)
        	{
        		this.mTextureRegionSheet[cnt] = TextureRegionFactory.extractFromTexture(mTextureSheet, x*128, y*128, 128, 128);
        		cnt++;
        	}	
    	
    	}
    	//this.mBackTex = new Texture(512,512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
    	//this.mBackTexReg = TextureRegionFactory.createFromAsset(this.mBackTex, this, "gfx/snow.png", 0, 0);
    	//this.mBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetTextureSource(this, "gfx/snow.png"));
		this.mTexturePlayer = new Texture(512,512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
    	this.mTiledTexturePlayer = TextureRegionFactory.createTiledFromAsset(this.mTexturePlayer, this, "gfx/player.png", 0, 0, 3, 3);
    	
    	this.mOnScreenControlTexture = new Texture(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mOnScreenControlBaseTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "gfx/onscreen_control_base.png", 0, 0);
		this.mOnScreenControlKnobTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "gfx/onscreen_control_knob.png", 128, 0);
		
		this.mFontTexture = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 12, true, Color.BLACK);
		
		this.mFontTextureScore = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFontScore = new Font(this.mFontTextureScore, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 46, true, Color.RED);
		
		this.mEngine.getTextureManager().loadTextures(this.mFontTexture,mFontTextureScore);
		this.mEngine.getFontManager().loadFont(this.mFont);
		this.mEngine.getFontManager().loadFont(this.mFontScore);
		
		
		this.mFlagsRightTexture = new Texture(64,64,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFlagsLeftTexture = new Texture(64,64,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mLeftTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mFlagsLeftTexture, this, "gfx/left.png", 0, 0, 2, 1);
		this.mRightTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mFlagsRightTexture, this, "gfx/right.png", 0, 0, 2, 1);
		this.mStartTexture = new Texture(256,256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFinishTexture = new Texture(256,256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mStartTextReg = TextureRegionFactory.createFromAsset(this.mStartTexture, this, "gfx/start.png", 0, 0);
			this.mFinTextReg = TextureRegionFactory.createFromAsset(this.mFinishTexture, this, "gfx/finish.png", 0, 0);

			this.mRanger = new Texture(512,512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
			this.mRangerTextReg = TextureRegionFactory.createTiledFromAsset(this.mRanger, this, "gfx/npcranger.png", 0, 0, 4, 3);
		
			
			this.mMenuText = new Texture(256,256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
			this.mMenuRestartReg = TextureRegionFactory.createFromAsset(this.mMenuText, this, "gfx/m_restart.png", 0, 0);
			this.mMenuOptionsReg = TextureRegionFactory.createFromAsset(this.mMenuText, this, "gfx/m_options.png", 0, 64);
			this.mMenuHelpReg = TextureRegionFactory.createFromAsset(this.mMenuText, this, "gfx/m_help.png", 0, 128);
			this.mMenuExitReg = TextureRegionFactory.createFromAsset(this.mMenuText, this, "gfx/m_exit.png", 0, 192);
			
			this.mSplashText = new Texture(1024,1024,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
			this.mSplashtextReg = TextureRegionFactory.createFromAsset(this.mSplashText, this, "gfx/into_background.jpg", 0, 0);
        this.mEngine.getTextureManager().loadTextures(mTextureSheet,mTexturePlayer,mSplashText, mOnScreenControlTexture,mRanger,mMenuText,mFinishTexture,mStartTexture,mFlagsLeftTexture,mFlagsRightTexture);
    	
        Drk_POOL = new ObjectPoolDrk(mTextureRegionSheet);
        
        Log.v("Coin", "onloadres end");

        //this.mTexture = new Texture(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        //this.mSpriteTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "gfx/tiles.png", 0, 0);

        //this.mEngine.getTextureManager().loadTexture(this.mTexture);
    }
    Random r = new Random();
	private ObjectSprite AddNewStaticObject()
	{
		
		Boolean temp = true;
		final ObjectSprite spr = Drk_POOL.obtainPoolItem();//op.obtainPoolItem();
		
		spr.setScale(.33f);
		while(temp)
		{
			spr.setPosition((mPlayer.getX() - CAMERA_WIDTH) + r.nextInt(1000), (mPlayer.getY() + 450 + r.nextInt(1000)));
			//spr.setPosition((float) ((this.mPlayer.getX() - CAMERA_WIDTH / 1.5) + r.nextInt((int)(CAMERA_WIDTH * 1.8))), mPlayer.getY() + CAMERA_HEIGHT / 2 + r.nextInt(400));
			temp = false;
			for(ObjectSprite os : myobjects) {
				if(CheckCircCol(spr.getX() + 16,spr.getY()+ 16,os.getX()+ 16,os.getY()+ 16,40)) {
					temp = true;
					break;
				}
			}
			
		}
		//Log.v(TAG,"Current trees: " + myobjects.size() + "Object Pos X:" + spr.getX() + "Y:" + spr.getY());
		//Body body;
		//final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
		//body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, spr, BodyType.StaticBody, objectFixtureDef);
		this.getEngine().getScene().attachChild(spr);
		//this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(spr, body, true, true));
		
		
		return spr;
	}
	
	private Boolean CheckCircCol(float x1, float y1, float x2, float y2,int range) {
		
		final float x = x1 - x2;
		final float y = y1 - y2;
		final double dist = Math.sqrt((x * x) + (y*y));
		//Log.v(TAG,"COORDS" + x1 + "y " + y1 + " x2" + x2 + "y" + y2 + "Distance between objs =" + dist);
		return dist <= (12 + range);
		//return false;
		
	}
	
	private Boolean CheckFlagsCol(float x1, float y1, float x2, float y2) {
		
		final float x = x1 - x2;
		final float y = y1 - y2;
		final double dist = Math.sqrt((x * x) + (y*y));
		//Log.v(TAG,"COORDS" + x1 + "y " + y1 + " x2" + x2 + "y" + y2 + "Distance between objs =" + dist);
		return dist <= (12 + 110);
		//return false;
		
	}
	private DecimalFormat df = new DecimalFormat();
	private ArrayList<AnimatedSprite> aLeft = new ArrayList<AnimatedSprite>();
	private ArrayList<AnimatedSprite> aRight = new ArrayList<AnimatedSprite>();
	private Boolean checkCol()
	{
		
		//if(bInair) { return false; } // replace this we can only jump rocks etc
		if(GameMode == 0) {
			// need a better way
			// check collides with starf flags
			if(CheckFlagsCol(mPlayer.getX() + 16,mPlayer.getY()+ 16,slalomStart.getX()+ 16,slalomStart.getY()+ 16)) {
				GameMode = 2;
				//Toast.makeText(this, "Slalom!", Toast.LENGTH_LONG).show();
				for(int i = 0; i < 40; i++) {
					aLeft.add(new AnimatedSprite(slalomStart.getX() - 25 + r.nextInt(75),(i * 300) + (slalomStart.getY() + 500) + r.nextInt(150),this.mLeftTextureRegion.clone()));
					aRight.add(new AnimatedSprite(slalomStart.getX() - 25 + r.nextInt(50),((i+1) * 300) + (slalomStart.getY() + 500) + r.nextInt(150),this.mRightTextureRegion.clone()));
										
				i++;
				}
				for(int i = 0; i < 20;i++) {
					this.getEngine().getScene().attachChild(aLeft.get(i));
					this.getEngine().getScene().attachChild(aRight.get(i));
					
				}
				finish = new Sprite(slalomStart.getX() - 25 + r.nextInt(50),aRight.get(19).getY() + 500,this.mFinTextReg);
				//finish = new Sprite(CAMERA_WIDTH / 3,650 + (500*10),this.mFinTextReg);
				Log.v(TAG,"SlalomStart!");
				// add flags here to dodge
			} else if(CheckFlagsCol(mPlayer.getX() + 16,mPlayer.getY()+ 16,freestyleStart.getX()+ 16,freestyleStart.getY()+ 16)) {
				GameMode = 1;
				//Toast.makeText(this, "FreeStyle!", Toast.LENGTH_LONG).show();
				
				finish = new Sprite(CAMERA_WIDTH / 3,650 + (500*10),this.mFinTextReg);
				Log.v(TAG,"FreeStyleStart!" + finish.getY());
				this.getEngine().getScene().attachChild(finish);
	
			}

		}
		if(GameMode == 1) {
			if(CheckFlagsCol(mPlayer.getX() + 16,mPlayer.getY()+ 16,finish.getX()+ 16,finish.getY()+ 16) || mPlayer.getY() >= finish.getY()) {
				Log.v(TAG,"FreeStyleend via Coll");
				GameMode = 0;
				this.fpsText3.setText(df.format(runtime) + "!");
				fpsText3.setVisible(true);
				scene.registerUpdateHandler(new TimerHandler(5.0f, false, new ITimerCallback() {
					@Override
					public void onTimePassed(final TimerHandler pTimerHandler) {
						//Log.v(TAG,"Player coords X:" + mPlayer.getX() + "Y:" + mPlayer.getY());
						fpsText3.setText("");
						fpsText3.setVisible(false);
						
						
						
					}
				}));
				
			}
		}
		if(GameMode == 2) {
			
			for(AnimatedSprite os : aLeft) {
				if(os.getCurrentTileIndex() == 1) { continue; }
				if(os.getY() + 14 <= mPlayer.getY()) {if(os.getX() + 14 > mPlayer.getX()) {os.setCurrentTileIndex(1);nSlalomScore++;} }
			}
			for(AnimatedSprite os : aRight) {
				if(os.getCurrentTileIndex() == 1) { continue; }
				if(os.getY() + 14 <= mPlayer.getY()) {if(os.getX() + 14 < mPlayer.getX()) {os.setCurrentTileIndex(1);nSlalomScore++;} }
			}
			if(CheckFlagsCol(mPlayer.getX() + 16,mPlayer.getY()+ 16,finish.getX()+ 16,finish.getY()+ 16) || mPlayer.getY() >= finish.getY()) {
				//Log.v(TAG,"Slalomend via Coll");
				GameMode = 0;
				for(AnimatedSprite os : aLeft) {os.detachSelf(); }
				for(AnimatedSprite os : aRight) {os.detachSelf(); }
				aLeft.clear();
				aRight.clear();
				this.fpsText3.setText(nSlalomScore + "! Time: " + df.format(runtime));
				fpsText3.setVisible(true);
				scene.registerUpdateHandler(new TimerHandler(4.0f, false, new ITimerCallback() {
					@Override
					public void onTimePassed(final TimerHandler pTimerHandler) {
						//Log.v(TAG,"Player coords X:" + mPlayer.getX() + "Y:" + mPlayer.getY());
						fpsText3.setText("");
						fpsText3.setVisible(false);
						
						
						
					}
				}));
				
			}
		}
		for(ObjectSprite os : myobjects) {
			if(!os.Collide){continue; }
			
						if(CheckCircCol(mPlayer.getX() + 16,mPlayer.getY()+ 16,os.getX()+ 16,os.getY()+ 16,12)) {
							if(os.bSlow) {if(bInair){score++;continue;};nSpeedBonus = -2;scene.registerUpdateHandler(new TimerHandler(.60f, false, new ITimerCallback() {
								@Override
								public void onTimePassed(final TimerHandler pTimerHandler) {
									//Log.v(TAG,"Player coords X:" + mPlayer.getX() + "Y:" + mPlayer.getY());
									nSpeedBonus = 0;
									
									
									
								}
							})); continue;}
							if(bInair && os.bJumpable) { score++; os.Collide = false; continue; }
				mPlayer.setCurrentTileIndex(7);
				scene.registerUpdateHandler(new TimerHandler(.60f, false, new ITimerCallback() {
					@Override
					public void onTimePassed(final TimerHandler pTimerHandler) {
						//Log.v(TAG,"Player coords X:" + mPlayer.getX() + "Y:" + mPlayer.getY());
						mPlayer.setCurrentTileIndex(6);
						
						
						
					}
				}));
				os.Collide = false;
				//Log.v(TAG,"Collide!");
				return true;
			}
		}
		
		return false;
		
	}
	private byte nSpeedBonus = 0;private int nSlalomScore = 0;
	private void UpdatePlayerPos(){
		switch(mPlayer.getCurrentTileIndex())
		{
    case 0:
    	if(mPlayer.getY() < 600) {mPlayer.setPosition(mPlayer.getX(), mPlayer.getY() + 1 + nSpeedBonus);} else {mPlayer.setPosition(mPlayer.getX(), mPlayer.getY() + 4 + nSpeedBonus);}
    	
		break;
	case 1:
		mPlayer.setPosition(mPlayer.getX() + 2 + nSpeedBonus, mPlayer.getY() + 2 + nSpeedBonus);
		break;
	case 2:
		mPlayer.setPosition(mPlayer.getX() - 2 + nSpeedBonus, mPlayer.getY() + 2 + nSpeedBonus);
		break;
	case 3:
		mPlayer.setPosition(mPlayer.getX() + 1 + nSpeedBonus, mPlayer.getY() + 3 + nSpeedBonus);
		break;
	case 4:
		mPlayer.setPosition(mPlayer.getX() - 1 + nSpeedBonus, mPlayer.getY() + 3 + nSpeedBonus);
		break;
	case 8:
		mPlayer.setPosition(mPlayer.getX(), mPlayer.getY() + 7 + nSpeedBonus);
		break;
		}
		
		
	}
	private int score = 0;
    private float runtime = 0;
    private int GameMode = 0; // 0 = none 1 = freestyle 2 = slalom
    private ArrayList<ObjectSprite> myobjects = new ArrayList<ObjectSprite>();
    private ArrayList<ObjectSprite> delus = new ArrayList<ObjectSprite>();
    private void updateSpritePosition(float pSecondsElapsed) {
    	this.mCamera.setCenter(mPlayer.getX()+ 64, mPlayer.getY() + (CAMERA_HEIGHT / 3));
    	if(!GameState)
    	{
    		return; // game has not started
    	}
    	
    
		// Main Loop
    	if(GameMode == 1 || GameMode == 2)
    	{
    	runtime += pSecondsElapsed;
    	}
    	UpdatePlayerPos();
    	nDistance = (mPlayer.getY() - 650) / 10; 
    	 if(nDistance < 0) { nDistance = 0; }
    	 
    	for(ObjectSprite os : myobjects) {
			os.Update(mPlayer);
			if (os.delme) {Drk_POOL.recyclePoolItem(os); Log.v(TAG,"unRecyle count =" + Drk_POOL.getUnrecycledCount()); delus.add(os);}
		}
    	for(ObjectSprite os : delus) {
    		myobjects.remove(os);
    	}
    	delus.clear();
    	
    	// moved check col down, wont check cols for items were gonna remove.
    	if(checkCol()) {
    		// we collided
    		if(GameMode == 1)
    		{
    			score = score - 1;
    		}
    	}
	
    		if(nDistance < 20) { return; } // Dont spawn anything yet;
    		
    		if(myobjects.size() < nDistance / 2 && myobjects.size()< 50) {
    			myobjects.add(AddNewStaticObject()); // adding to array
    				
    		}
    		
	
    }

    public Scene onLoadScene() {
    	Log.v("Coin", "onLoadScene");
    	df = new DecimalFormat("#0.00");
        //sensorManager = (SensorManager) this.getSystemService(this.SENSOR_SERVICE);
        //sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_GAME);
    	final FPSCounter fpsCounter = new FPSCounter();
        this.mEngine.registerUpdateHandler(new FPSLogger());
        this.mEngine.registerUpdateHandler(new TimerHandler(0.0166666666666667f, true, new ITimerCallback() {
			@Override
			public void onTimePassed(final TimerHandler pTimerHandler) {
				updateSpritePosition(0.0166666666666667f);//0.0166666666666667f
			}
        }));
        this.createMenuScene();
        final Scene scene = new Scene();
       /* back1 = new Sprite(-50,0,mBackTexReg);
        while(back1.getHeight() < CAMERA_HEIGHT * 1.5) {
        	back1.setSize(back1.getWidth() + 5, back1.getHeight() + 5);
        }
        back2 = new Sprite(-50,back1.getHeight(),mBackTexReg);
        back2.setSize(back1.getWidth(), back1.getHeight());
        //scene.getLastChild().attachChild(back2);
        //scene.getLastChild().attachChild(back1);
        Log.v("Coin", "back1 pos set to " + back1.getX() + "  " + back1.getY());
        Log.v("Coin", "back2 pos set to " + back2.getX() + "  " + back2.getY());*/
        //scene.setBackground(this.mBackground);
        scene.setBackground(new ColorBackground(1.2f, 1.3f, 1.4f));//(0.2f, 0.3f, 0.4f));
        
        
        final ChangeableText fpsText = new ChangeableText(5, 5, this.mFont, "Distance: 0    Time: 0", "Distance: XXXXX Time: XXXX".length());
        final ChangeableText fpsText2 = new ChangeableText(5, 20, this.mFont, "Score:", "Score: XXX".length());
        fpsText3 = new ChangeableText(CAMERA_HEIGHT / 3, (CAMERA_WIDTH / 2) - 50, this.mFontScore, "", "Score: Time:".length());
		HUD myhud = new HUD();
		myhud.attachChild(fpsText);
		myhud.attachChild(fpsText2);
		myhud.attachChild(fpsText3);
		scene.registerUpdateHandler(new TimerHandler(1.1f, true, new ITimerCallback() {
			@Override
			public void onTimePassed(final TimerHandler pTimerHandler) {
				//Log.v(TAG,"Player coords X:" + mPlayer.getX() + "Y:" + mPlayer.getY());
				fpsText.setText("Distance: " + (int)nDistance + "   Time: " + (int)runtime);
				if(nSlalomScore == 0) {
					fpsText2.setText("Score: " + score);
				} else {
					fpsText2.setText("Score: " + nSlalomScore);
				}
				
				
				
				
			}
		}));

		
        sX = (CAMERA_WIDTH - 128) / 2;
        sY = (CAMERA_HEIGHT - 32) / 5;

        mPlayer = new AnimatedSprite(sX, sY, mTiledTexturePlayer);
        
        //final PhysicsHandler physicsHandler = new PhysicsHandler(mPlayer);
        //mPlayer.registerUpdateHandler(physicsHandler);
        
        //this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, 0), false);//SensorManager.GRAVITY_EARTH
		//Body body;
		//final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
		//body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, mPlayer, BodyType.DynamicBody, objectFixtureDef);
		
		//this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mPlayer, body, true, true));
		
        //scene.registerUpdateHandler(this.mPhysicsWorld);
        mPlayer.setScale(0.33f);
        //scene.getLastChild().attachChild(mPlayer);
        //this.mCamera.setChaseEntity(mPlayer);
        freestyleStart = new Sprite(5, CAMERA_HEIGHT - 10,this.mStartTextReg);
        
        slalomStart = new Sprite(5 + 256 + 10, CAMERA_HEIGHT - 10,this.mStartTextReg);
        
        final Sprite freestyleStartsign = new Sprite(80,CAMERA_HEIGHT - 60,this.mTextureRegionSheet[13]);   
        final Sprite slalomStartsign = new Sprite(slalomStart.getX() + 80, CAMERA_HEIGHT - 60,this.mTextureRegionSheet[12]);
        freestyleStartsign.setScale(0.75f);
        slalomStartsign.setScale(0.75f);
        scene.attachChild(freestyleStart);
        scene.attachChild(slalomStart);
        scene.attachChild(freestyleStartsign);
        scene.attachChild(slalomStartsign);
        
        scene.attachChild(mPlayer);
        
        
        
        final DigitalOnScreenControl digitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() {
			@Override
			public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
				//physicsHandler.setVelocity(pValueX * 50, pValueY * 80);
				
				inputx = pValueX;
				inputy = pValueY;
				
				
			}
		});
		digitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		digitalOnScreenControl.getControlBase().setAlpha(0.5f);
		digitalOnScreenControl.getControlBase().setScaleCenter(0, 128);
		digitalOnScreenControl.getControlBase().setScale(1.25f);
		digitalOnScreenControl.getControlKnob().setScale(1.25f);
		digitalOnScreenControl.refreshControlKnobPosition();
		myhud.setChildScene(digitalOnScreenControl);
		//scene.setChildScene(digitalOnScreenControl);
		scene.setOnSceneTouchListener(this);
		scene.registerUpdateHandler(new TimerHandler(.10f, true, new ITimerCallback() {
			@Override
			public void onTimePassed(final TimerHandler pTimerHandler) {
				//Log.v(TAG,"FPS UPDATED");
				updatecontrols();
			}
		}));
		mCamera.setHUD(myhud);
        Log.v("Coin", "onLoadScene end" + sX + "--" + sY);
        splashscreen = new Sprite(0,0,this.mSplashtextReg);
        splashscreen.setSize(CAMERA_WIDTH, CAMERA_HEIGHT + 25);
        scene.attachChild(splashscreen);
        this.scene = scene;
        return scene;
    }
Scene scene;Sprite splashscreen;ChangeableText fpsText3;

@Override
    public void onLoadComplete() {
Log.v(TAG,"Load COmplete");
aLeft.ensureCapacity(20);
aRight.ensureCapacity(20);
    	
    }
float inputx = 0;
float inputy = 0;
    /*public void onSensorChanged(SensorEvent event) {
        synchronized (this) {
            switch (event.sensor.getType()) {
                case Sensor.TYPE_ACCELEROMETER:
                	float x = event.values[1];
                	float y = event.values[0];
                	if(oldx == 0 && oldy == 0)
                	{
                		Log.v("Coin", "old x/y were 0");
                		oldx = x;
                		oldy = y; // gets our baseline 1st run thru
                	}
                	if((x > oldx + .5) || (x < oldx - .5)) {
                		Log.v("Coin", "X change. oldx: " + oldx + " newx = " + x);
                		accellerometerSpeedX = x;
                		mPlayer.setCurrentTileIndex(1);
                		 if((x > oldx + 1) || (x < oldx - 1)) {mPlayer.setCurrentTileIndex(2); }
                		 
                		 if(x > oldx){  mPlayer.setFlippedHorizontal(true);	}
                		oldx = x;
                		
                	} else {
                		mPlayer.setCurrentTileIndex(0);
                		accellerometerSpeedX = 0;//(int)event.values[1];
                        accellerometerSpeedY = 0;//(int)event.values[0];
                	}
                	break;
                	
            }
        }
    }*/
public Boolean GameState = false;
@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
	     
     if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
         if(!GameState) {
        	 Log.v(TAG,"Setting state to run");
        	 if(splashscreen != null) {
            	 splashscreen.setVisible(false);
            	 splashscreen.detachSelf();
            	 splashscreen = null;
        	 }

        	 GameState = true;
        	 return true;
        	 }
         //Log.v(TAG,"Do jump");
         if(mPlayer.getCurrentTileIndex() != 8 && mPlayer.getCurrentTileIndex() != 7){
        	 bInair = true;
        	 mPlayer.setCurrentTileIndex(8);
        	 pScene.registerUpdateHandler(new TimerHandler(.50f, false, new ITimerCallback() {
     			@Override
     			public void onTimePassed(final TimerHandler pTimerHandler) {
     				mPlayer.setCurrentTileIndex(0);
     				bInair = false;
     			}
     		})); 
         }

     	 //this.player.setPosition(targetTile.getTileX(), targetTile.getTileY());
     }
     return true;
}
private Boolean bInair = false;

   private void updatecontrols()
   {
	   if(inputx == 1) {
			switch(mPlayer.getCurrentTileIndex()) {
			case 0:
				mPlayer.setCurrentTileIndex(3);
				break;
			case 1:
				mPlayer.setCurrentTileIndex(5);
				break;
			case 2:
				mPlayer.setCurrentTileIndex(4);
				break;
			case 3:
				mPlayer.setCurrentTileIndex(1);
				break;
			case 4:
				mPlayer.setCurrentTileIndex(0);
				break;
			case 5:
				mPlayer.setPosition(mPlayer.getX() + 2, mPlayer.getY());
				break;
			case 6:
				mPlayer.setCurrentTileIndex(2);
				break;
			}
		}
		if(inputx == -1) {
			switch(mPlayer.getCurrentTileIndex()) {
			case 0:
				mPlayer.setCurrentTileIndex(4);
				break;
			case 1:
				mPlayer.setCurrentTileIndex(3);
				break;
			case 2:
				mPlayer.setCurrentTileIndex(6);
				break;
			case 3:
				mPlayer.setCurrentTileIndex(0);
				break;
			case 4:
				mPlayer.setCurrentTileIndex(2);
				break;
			case 5:
				mPlayer.setCurrentTileIndex(1);
				break;
			case 6:
				mPlayer.setPosition(mPlayer.getX() - 2, mPlayer.getY());
				break;
			}
		}
		if(inputy == 1) {
			if(mPlayer.getCurrentTileIndex() != 7) {mPlayer.setCurrentTileIndex(0); }
			
		}
		if (inputy == -1) {
			mPlayer.setCurrentTileIndex(6);
		}
	inputx = 0;
	inputy = 0;
   }
    // ===========================================================
    // Methods
    // ===========================================================

   @Override
	public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
		if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) {
			Log.v(TAG,"Menu hit");
			if(this.getEngine().getScene().hasChildScene()) {
				/* Remove the menu and reset it. */
				GameState = true;
				this.mMenuScene.back();
			} else {
				/* Attach the menu. */
				GameState = false;
				this.scene.setChildScene(this.mMenuScene, false, true, true);
			}
			return true;
		}
		else {
			return super.onKeyDown(pKeyCode, pEvent);
		}
	}
private void resett()
{
	this.mPlayer.setScale(0.33f);
	this.mPlayer.setCurrentTileIndex(0);
	nDistance = 0;
	runtime = 0;
	score = 0;
	GameState = false;
	GameMode = 0;
	sX = (CAMERA_WIDTH - 128) / 2;
    sY = (CAMERA_HEIGHT - 32) / 5;
    mPlayer.setPosition(sX, sY);
	for(ObjectSprite os : myobjects) {
		os.delme = true;
		if (os.delme) {Drk_POOL.recyclePoolItem(os); Log.v(TAG,"unRecyle count =" + Drk_POOL.getUnrecycledCount()); delus.add(os);}
	}
	for(ObjectSprite os : delus) {
		myobjects.remove(os);
	}
	delus.clear();  
    myobjects.clear();
    	
	
	}
	@Override
	public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) {
		switch(pMenuItem.getID()) {
			case MENU_RESET:
				/* Restart the animation. */
				this.getEngine().getScene().reset();
				resett();
				/* Remove the menu and reset it. */
				this.getEngine().getScene().clearChildScene();
				this.mMenuScene.reset();
				
				return true;
				
			case MENU_OPTIONS:
				return true;
			case MENU_HELP:
				return true;
			case MENU_QUIT:
				/* End Activity. */
				this.finish();
				return true;
			default:
				return false;
		}
	}

	// ===========================================================
	// Methods
	// ===========================================================

	protected void createMenuScene() {
		this.mMenuScene = new MenuScene(this.mCamera);

		final SpriteMenuItem resetMenuItem = new SpriteMenuItem(MENU_RESET, this.mMenuRestartReg);
		resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(resetMenuItem);

		final SpriteMenuItem optionsMenuItem = new SpriteMenuItem(MENU_OPTIONS, this.mMenuOptionsReg);
		optionsMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(optionsMenuItem);
		
		final SpriteMenuItem helpMenuItem = new SpriteMenuItem(MENU_HELP, this.mMenuHelpReg);
		helpMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(helpMenuItem);
		
		final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_QUIT, this.mMenuExitReg);
		quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(quitMenuItem);

		this.mMenuScene.buildAnimations();

		this.mMenuScene.setBackgroundEnabled(false);

		this.mMenuScene.setOnMenuItemClickListener(this);
	}

    // ===========================================================
    // Inner and Anonymous Classes
    // ===========================================================  
	 AdView adView;

		private static String MY_AD_UNIT_ID = "a14e00a0b9e9e39";
	    @Override
	    protected void onSetContentView() {


	        final FrameLayout frameLayout = new FrameLayout(this);
	        final FrameLayout.LayoutParams frameLayoutLayoutParams =
	                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
	                                             FrameLayout.LayoutParams.FILL_PARENT);
	      
	        	adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);
	       
	        

	        adView.refreshDrawableState();
	        adView.setVisibility(AdView.VISIBLE);
	        final FrameLayout.LayoutParams adViewLayoutParams =
	                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
	                                             FrameLayout.LayoutParams.WRAP_CONTENT,
	                                             Gravity.CENTER_HORIZONTAL|Gravity.TOP);
	        // getHeight returns 0
	        // <!-- m --><a class="postlink" href="http://groups.google.com/group/admob-publisher-discuss/browse_thread/thread/d999ccc50c637d5/a92630a874df3472">http://groups.google.com/group/admob-pu ... a874df3472</a><!-- m -->
	        int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
	                getResources ().getDisplayMetrics ());
	        // top of AD is at middle of the screen
	        //adViewLayoutParams.bottomMargin = 20;
	        Log.v(TAG, "Adview height : " + height);
	        Log.v(TAG, "Adview size {x:" + adView.getWidth() + ", y: " + adView.getHeight()+ "}");
	        //adView.setVerticalGravity(Gravity.TOP);
				AdRequest adRequest = new AdRequest();
			        adRequest.addTestDevice( AdRequest.TEST_EMULATOR);
					adView.loadAd(adRequest);
	        
	        

	        this.mRenderSurfaceView = new RenderSurfaceView(this);
	        mRenderSurfaceView.setRenderer(mEngine);

	        final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams =
	                new FrameLayout.LayoutParams(super.createSurfaceViewLayoutParams());
	        surfaceViewLayoutParams.gravity = Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM;
	        surfaceViewLayoutParams.topMargin = 50;
	        frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
	        frameLayout.addView(adView, adViewLayoutParams);

	        this.setContentView(frameLayout, frameLayoutLayoutParams);

	        
	    }



}